﻿using System;
using System.Collections.Generic;
using UnityEngine;

public class EventTrigger
{
    private string triggerName;
    private Dictionary<string, List<Action<object[]>>> actionsDict = new Dictionary<string, List<Action<object[]>>>();

    public EventTrigger(string triggerName)
    {
        this.triggerName = triggerName;
    }

    public void AddListener(string eventName, Action<object[]> action)
    {
        if (!actionsDict.ContainsKey(eventName))
        {
            actionsDict[eventName] = new List<Action<object[]>>();
        }
        if (!actionsDict[eventName].Contains(action))
        {
            actionsDict[eventName].Add(action);
        }
        else
        {
            Debug.LogWarning(string.Format("{0}已包含此方法", triggerName));
        }
    }

    public void RemoveListener(string eventName, Action<object[]> action)
    {
        if (actionsDict.ContainsKey(eventName) && actionsDict[eventName].Contains(action))
        {
            actionsDict[eventName].Remove(action);
        }
        else
        {
            Debug.LogWarning(string.Format("{0}没有对应的方法", triggerName));
        }
    }

    public void Dispatch(string eventName, object[] args)
    {
        if (actionsDict.ContainsKey(eventName))
        {
            try
            {
                for (int i = 0; i < actionsDict[eventName].Count; i++)
                {
                    actionsDict[eventName][i](args);
                }
            }
            catch (Exception e)
            {
                Debug.LogError(e.Message);
            }
        }
    }
}